package com.example.havi.helper;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.example.havi.bean.HyChatUser;
import com.example.havi.interfaces.HyphenateLibraryCallBack;
import com.example.havi.interfaces.LoginCallBack;
import com.example.havi.util.ChatToastUtil;
import com.example.havi.util.LogUtil;
import com.example.havi.util.PlayerUtil;
import com.tencent.imcore.TextElem;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConnListener;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMElem;
import com.tencent.imsdk.TIMElemType;
import com.tencent.imsdk.TIMFriendshipSettings;
import com.tencent.imsdk.TIMGroupSettings;
import com.tencent.imsdk.TIMImageElem;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMMessageListener;
import com.tencent.imsdk.TIMRefreshListener;
import com.tencent.imsdk.TIMSdkConfig;
import com.tencent.imsdk.TIMSoundElem;
import com.tencent.imsdk.TIMTextElem;
import com.tencent.imsdk.TIMUser;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.imsdk.TIMUserStatusListener;
import com.tencent.imsdk.ext.message.TIMUserConfigMsgExt;

import java.util.List;

public class ChatHelper {
    private static ChatHelper instance;
    private Context appContext;
    private HyChatUser hyChatUser;
    private HyphenateLibraryCallBack hyphenateLibraryCallBack;
    private TIMMessageListener messageListener;
    private String TAG = "mango";
    public String mIdentifier;

    public static ChatHelper getInstance() {
        if (instance == null) {
            instance = new ChatHelper();
        }
        return instance;
    }

    public void init(Context appContext, HyphenateLibraryCallBack callBack,String appid) {
        this.appContext = appContext;
        hyphenateLibraryCallBack = callBack;

        TIMSdkConfig config = new TIMSdkConfig(Integer.valueOf(appid))
                .enableCrashReport(false) // 禁用Crash上报
                .enableLogPrint(true)   // 控制台打印日志
                .setLogLevel(TIMLogLevel.DEBUG)  // 日志等级
                .setLogPath(Environment.getExternalStorageDirectory().getPath() + "/justfortest/");   // 日志路径

        // 初始化sdk
        boolean init = TIMManager.getInstance().init(appContext, config);
        if (init)
        {
            Log.e(TAG,"腾讯im已经初始化");
        }
        // 初始化消息配置
        initChatConfit();
        EmojiDataHelper.getInstence().init(appContext);
        registerMessageListener();  //注册消息接收监听
    }

    private void initChatConfit() {
        //基本用户配置
        TIMUserConfig userConfig = new TIMUserConfig()
                //设置群组资料拉取字段
                .setGroupSettings(new TIMGroupSettings())
                //设置资料关系链拉取字段
                .setFriendshipSettings(new TIMFriendshipSettings())
                //设置用户状态变更事件监听器
                .setUserStatusListener(new TIMUserStatusListener() {
                    @Override
                    public void onForceOffline() {
                        //被其他终端踢下线
                        Log.i(TAG, "onForceOffline");
                    }

                    @Override
                    public void onUserSigExpired() {
                        //用户签名过期了，需要刷新 userSig 重新登录 SDK
                        Log.i(TAG, "onUserSigExpired");
                    }
                })
                //设置连接状态事件监听器
                .setConnectionListener(new TIMConnListener() {
                    @Override
                    public void onConnected() {
                        Log.i(TAG, "onConnected");
                    }

                    @Override
                    public void onDisconnected(int code, String desc) {
                        Log.i(TAG, "onDisconnected");
                    }

                    @Override
                    public void onWifiNeedAuth(String name) {
                        Log.i(TAG, "onWifiNeedAuth");
                    }
                })
                //设置会话刷新监听器
                .setRefreshListener(new TIMRefreshListener() {
                    @Override
                    public void onRefresh() {
                        Log.i(TAG, "onRefresh");
                    }

                    @Override
                    public void onRefreshConversation(List<TIMConversation> conversations) {
                        Log.i(TAG, "onRefreshConversation, conversation size: " + conversations.size());
                    }
                });

//消息扩展用户配置
        userConfig = new TIMUserConfigMsgExt(userConfig)
                //禁用消息存储
                .enableStorage(true)
                //开启消息已读回执
                .enableReadReceipt(true);
        TIMManager.getInstance().setUserConfig(userConfig);

    }

    private void registerMessageListener() {
        TIMManager.getInstance().addMessageListener(messageListener = new TIMMessageListener() {
            @Override
            public boolean onNewMessages(List<TIMMessage> msgs) {
                for (TIMMessage message : msgs) {
                    // in background, do not refresh UI, notify it in notification bar
                    String sender = message.getSender();
                    if (sender.equals(mIdentifier)) { //登陆的时候会收到一条自己的 需要过滤掉
                        Log.e("song","接收到自己登录的信息");
                        continue;
                    }
                    PlayerUtil.INSTANCE.playerVibrator();
                    PlayerUtil.INSTANCE.playSystemMusic();
                    //显示消息通知
                    getLibraryCallBack().onNewMsg(message);
                    // 处理element
                    for(int i = 0; i < message.getElementCount(); ++i) {
                        TIMElem elem = message.getElement(i);
                        //获取当前元素的类型
                        TIMElemType elemType = elem.getType();
                        Log.d(TAG, "elem type: " + elemType.name());
                        if (elemType == TIMElemType.Text) {
                            //处理文本消息.
                            TIMTextElem e = (TIMTextElem) elem;
                            Log.e(TAG, "onNewMessages: 处理文本消息" );
                        } else if (elemType == TIMElemType.Image) {
                            //处理图片消息
                            TIMImageElem e = (TIMImageElem) elem;
                            Log.e(TAG, "onNewMessages: 处理图片消息" );
                        } else if (elemType == TIMElemType.Sound)
                        {
                            //处理声音消息消息
                            TIMSoundElem e = (TIMSoundElem) elem;
                            Log.e(TAG, "onNewMessages: 处理声音消息消息" );

                        }else if (elemType == TIMElemType.Custom)
                        {
                            //处理自定义消息
                            TIMSoundElem e = (TIMSoundElem) elem;
                            Log.e(TAG, "onNewMessages: 处理自定义消息" );
                        }
                    }
                }
                return false; //返回true将终止回调链，不再调用下一个新消息监听器
            }
        });
        Log.e(TAG, "registerMessageListener: 配置消息接收器成功" );

    }

    public Context getAppContext() {
        return appContext;
    }

    public HyphenateLibraryCallBack getLibraryCallBack() {
        return hyphenateLibraryCallBack;
    }

    /**
     * 同步账号信息
     *
     * @param userInfo
     */
    public void syncChatUserInfo(HyChatUser userInfo) {
        this.hyChatUser = userInfo;
    }

    public HyChatUser getHyChatUser() {
        return hyChatUser==null?new HyChatUser():hyChatUser;
    }


    public void login(final String identifier, String userSig, final LoginCallBack callBack){
        TIMUser timUser = new TIMUser();
        timUser.setIdentifier(identifier);
        // identifier为用户名，userSig 为用户登录凭证
        TIMManager.getInstance().login(identifier, userSig, new TIMCallBack() {
            @Override
            public void onError(int code, String desc) {
                //错误码 code 和错误描述 desc，可用于定位请求失败原因
                //错误码 code 列表请参见错误码表
                Log.e("chat", "登录聊天服务器失败！"+desc);
                ChatToastUtil.showToast(getAppContext(),"账号不可用,无法登陆 "+"identifier : "+identifier);
                callBack.onError(code,desc);
            }

            @Override
            public void onSuccess() {
//                EventBus.getDefault().post(new TIMLoginSuccessEvent());
                Log.e("chat", "登录聊天服务器成功！");
                callBack.onSuccess();
                mIdentifier = identifier;
            }
        });



    }

    public boolean isLogin() {
        return !TextUtils.isEmpty(TIMManager.getInstance().getLoginUser());
    }

    public void loginOutTIM(final LoginOutCallBack callBack) {
        TIMManager.getInstance().logout(new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
                if (callBack != null) {
                    callBack.loginOutFailure(s);
                }
            }

            @Override
            public void onSuccess() {
                if (callBack != null) {
                    callBack.loginOutSuccess();
                    mIdentifier = "";
                }
            }
        });
    }

    public interface LoginOutCallBack {
        void loginOutSuccess();

        void loginOutFailure(String errorMsg);
    }
}
